package com.ruoyi.quartz.task;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.userlocation.CombatBlog;
import com.ruoyi.combat.domain.userlocation.CombatRelation;
import com.ruoyi.combat.domain.userlocation.CombatUser;
import com.ruoyi.combat.domain.userlocation.CombatWarn;
import com.ruoyi.combat.service.socialmedia.CombatCrawlService;
import com.ruoyi.combat.service.userlocation.ICombatBlogService;
import com.ruoyi.combat.service.userlocation.ICombatRelationService;
import com.ruoyi.combat.service.userlocation.ICombatUserService;
import com.ruoyi.combat.service.userlocation.ICombatWarnService;
import com.ruoyi.combat.util.CoordinateUtils;
import com.ruoyi.combat.util.JavacvUtils;
import com.ruoyi.combat.util.MethodUseUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.file.service.ISysFileService;
import com.ruoyi.quartz.util.CityUtil;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * 课题三 微博用户 博文、社交关系风险检测任务
 */
@Component("userLocationTask")
public class UserLocationTask {

    @Autowired
    private ICombatBlogService combatBlogService;
    @Autowired
    private CombatCrawlService combatCrawlService;
    @Autowired
    private ICombatRelationService combatRelationService;
    @Autowired
    private ICombatUserService combatUserService;
    @Autowired
    private MethodUseUtils methodUseUtils;

    @Autowired
    private ICombatWarnService combatWarnService;
    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysFileService sysFileService;

    private void checkUserRelation(String userId) {

        String jsonStr = buildRelation(userId);

        Map<String, Object> stringObjectMap = methodUseUtils.methodUseLogs(17L, jsonStr);
        //
        if (stringObjectMap.get("results") != null) {
            CombatUser combatUser1 = combatUserService.selectCombatUserByUserId(userId);
            String results = JSONUtil.toJsonStr(stringObjectMap.get("results"));
            List<Map> list1 = JSONUtil.toList(results, Map.class);
            if (list1.size() > 0) {
                checkAddress(userId, list1.get(0));
            }

            CombatUser combatUser = new CombatUser();
            combatUser.setId(combatUser1.getId());
            combatUser.setAfterAddress(results);
            combatUserService.updateCombatUser(combatUser);
            System.out.println();
        }
    }


    public String buildRelation(String userId) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Map> userMap = new HashMap<>();
        CombatUser combatUser = combatUserService.selectCombatUserByUserId(userId);

        String userHomeAddr = combatUser.getUserHomeAddr();
        userHomeAddr = getCity(userHomeAddr);
        if (StringUtils.isEmpty(userHomeAddr)) {
            String userWorkAddr = combatUser.getUserWorkAddr();
            userHomeAddr = getCity1(userWorkAddr);
        }

        Map<String, String> datas = new HashMap();
        datas.put("name", combatUser.getUserNickname());
        datas.put("city", userHomeAddr);
        userMap.put(combatUser.getUserId(), datas);


        CombatRelation combatRelation = new CombatRelation();
        combatRelation.setUserid(userId);
        List<CombatRelation> combatRelations = combatRelationService.selectCombatRelationList(combatRelation);

        List<Map<String, String>> list = new ArrayList<>();
        List<Map<String, String>> fake_user = new ArrayList<>();
        for (CombatRelation relation : combatRelations) {
            Map<String, String> data = new HashMap<>();
            String userid = relation.getUserid();
            String username = relation.getUsername();
            String userCity = relation.getUserCity();
            if (StringUtils.isEmpty(userHomeAddr)) {
                userCity = getCity1(userCity);
            }

            String targetid = relation.getTargetid();
            String targetName = relation.getTargetName();
            String targetCity = relation.getTargetCity();
            targetCity = getCity1(targetCity);
            if (StringUtils.isEmpty(targetCity)) {
                List<CombatBlog> blogsByUserId = combatBlogService.getBlogsByUserId(targetid);
                if (blogsByUserId.size() > 0) {
                    CombatBlog blog = blogsByUserId.get(0);
                    String reportContent = blog.getReportContent();
                    List<String> list1 = new ArrayList<>();
                    list1.add(reportContent);
                    Map<String, Object> stringObjectMap = methodUseUtils.methodUseLogs(15l, JSONUtil.toJsonStr(list1));
                    if (stringObjectMap != null) {
                        String locationPos = String.valueOf(stringObjectMap.get("city-district"));
                        String city1 = getCity1(locationPos);
                        if (StringUtils.isEmpty(city1)) {
                            continue;
                        }
                        targetCity = city1;
                    }else{
                        continue;
                    }
                }
            }
            relation.setTargetCity(targetCity);
            combatRelationService.updateCombatRelation(relation);
            data.put("toId", targetid);
            data.put("toName", targetName);
            data.put("toCity", targetCity);
            data.put("fromId", userid);
            data.put("fromName", username);
            data.put("fromCity", "");
            data.put("relation", "关注");
            list.add(data);
          /*  if (userMap.get(userId) == null) {
                Map<String, String> data1 = new HashMap<>();
                data1.put("userid", userid);
                data1.put("name", username);
                data1.put("city", userCity);
                fake_user.add(data1);
            }*/
            if (userMap.get(targetid) == null) {
                Map<String, String> data1 = new HashMap<>();
                data1.put("userid", targetid);
                data1.put("name", targetName);
                data1.put("city", targetCity);
                fake_user.add(data1);
            }
        }
        result.put("target_userid", userId);
        result.put("data", list);
        String jsonStr = JSONUtil.toJsonStr(result);
        return jsonStr;
    }

    //定位检测
    private String checkAddress(String userId, Map coordinate) {
        CombatUser combatUser = combatUserService.selectCombatUserByUserId(userId);

        String locationPos = String.valueOf(coordinate.get("predicted_city"));
        if (coordinate.get("lat") == null) {
            return "";
        }

        double lat = Double.parseDouble(String.valueOf(coordinate.get("lat")));
        double lng = Double.parseDouble(String.valueOf(coordinate.get("lng")));
        //与用户家庭、工作地址进行坐标进行比较；
        String userHomeLat = combatUser.getUserHomeLat();
        String userHomeLon = combatUser.getUserHomeLon();
        Long home = null;
        if (StringUtils.isNotEmpty(userHomeLat) && StringUtils.isNotEmpty(userHomeLon)) {
            double homeLat = Double.parseDouble(String.valueOf(userHomeLat));
            double homeLon = Double.parseDouble(String.valueOf(userHomeLon));
            home = CoordinateUtils.calculateGEODistance(lat, lng, homeLat, homeLon);
        }

        String userWorkLat = combatUser.getUserWorkLat();
        String userWorkLon = combatUser.getUserWorkLon();
        Long work = null;
        if (StringUtils.isNotEmpty(userWorkLat) && StringUtils.isNotEmpty(userWorkLon)) {
            double workLat = Double.parseDouble(String.valueOf(userWorkLat));
            double workLon = Double.parseDouble(String.valueOf(userWorkLon));
            work = CoordinateUtils.calculateGEODistance(lat, lng, workLat, workLon);
        }
        //插入警告记录
        if (home < 30 || work < 30) {
            CombatWarn combatWarn = new CombatWarn();
            combatWarn.setUserid(userId);
            combatWarn.setUsername(combatUser.getUserName());
            combatWarn.setLocationBasis("社交关系定位");
            combatWarn.setLocationLat(String.valueOf(lat));//定位纬度
            combatWarn.setLocationLon(String.valueOf(lng));//定位经度

            String leak = "家庭地址";
            if (work < home) {
                leak = "工作地址";
            }
            combatWarn.setLocationLeak(leak);//泄露地点
            combatWarn.setLocationPos(locationPos);//定位地点
            combatWarnService.insertCombatWarn(combatWarn);
        }
        return locationPos;
    }

    /**
     * 用户关系检测任务
     */
    public void checkUserRelationTask() {
        CombatUser combatUser = new CombatUser();
        combatUser.setUserType("重保用户");
        List<CombatUser> combatUsers = combatUserService.selectCombatUserList(combatUser);
        for (CombatUser user : combatUsers) {
            String userId = user.getUserId();
            checkUserRelation(userId);
        }
    }



    /**
     * 微博用户 博文、社交关系风险检测任务
     */
    public void checkBlogTask() {
        CombatUser combatUser = new CombatUser();
        combatUser.setUserType("重保用户");
        List<CombatUser> combatUsers = combatUserService.selectCombatUserList(combatUser);
        for (CombatUser user : combatUsers) {
            String userId = user.getUserId();
            String token = user.getToken();
            if (StringUtils.isNotEmpty(userId) && StringUtils.isNotEmpty(token)) {
                CombatBlog combatBlog = new CombatBlog();
                combatBlog.setUserId(userId);
                combatBlog.setStatus("0");
                List<CombatBlog> combatBlogs = combatBlogService.selectCombatBlogList(combatBlog);
                for (CombatBlog combatBlog1 : combatBlogs) {
                    try {
                        String reportContent = combatBlog1.getReportContent();
                        CombatWarn combatWarn2 = combatCrawlService.checkWeiboContent(15L, userId, reportContent);
                        if (combatWarn2 == null) {
                            combatWarn2 = new CombatWarn();
                            continue;
                        } else {
                            if (StringUtils.isNotEmpty(combatWarn2.getCheckResult())) {
                                combatBlog1.setTextAddress(combatWarn2.getCheckResult());
                            }
                        }
                        String blogId = combatBlog1.getBlogId();
                        if (combatWarn2.getLocationLeak() != null) {
                            combatWarn2.setBlogId(combatBlog1.getBlogId());
                            if (checkData(blogId)) {
                                combatWarnService.insertCombatWarn(combatWarn2);
                            }
                        }

                        String city = combatWarn2.getLocationPos();
                        city = getCity(city);

                        String city1 = getCity1(user.getUserHomeAddr());
                        String city2 = getCity1(user.getUserWorkAddr());
                        if(StringUtils.isEmpty(city)) {
                            if (StringUtils.isNotEmpty(city1)) {
                                city = city1;
                            } else if (StringUtils.isNotEmpty(city2)) {
                                city = city2;
                            }
                        }

                        if (StringUtils.isNotEmpty(city)) {
                            String reportImages = combatBlog1.getReportImages();
                            if (StringUtils.isNotEmpty(reportImages) && StringUtils.isNotEmpty(city)) {
                                String[] split = reportImages.split(",");
                                for (String url : split) {
                                    byte[] bytes = downloadPicture(url);
                                    String imgBase64 = Base64.getEncoder().encodeToString(bytes);
                                    //图像地理定位
//                                    CombatWarn combatWarn = combatCrawlService.checkWeiboImage(16L, userId, imgBase64, city);
                                    CombatWarn combatWarn = combatCrawlService.checkWeiboImage(48L, userId, imgBase64, city);
                                    if (combatWarn.getLocationLat() != null) {
                                        if (checkData(blogId)) {
                                            combatWarn.setBlogId(combatBlog1.getBlogId());
                                            combatWarnService.insertCombatWarn(combatWarn);
                                        }
                                    }
                                    if (StringUtils.isNotEmpty(combatWarn.getCheckResult())) {
                                        combatBlog1.setImageAddress1(combatWarn.getCheckResult());
                                    }
                                    //                                图像街景定位
//                                    CombatWarn combatWarn1 = combatCrawlService.checkWeiboImage(23L, userId, imgBase64, city);
                                    CombatWarn combatWarn1 = combatCrawlService.checkWeiboImage(47L, userId, imgBase64, city);
                                    if (combatWarn1.getLocationLat() != null) {
                                        if (checkData(blogId)) {
                                            combatWarn1.setBlogId(combatBlog1.getBlogId());
                                            combatWarnService.insertCombatWarn(combatWarn1);
                                        }
                                    }
                                    if (StringUtils.isNotEmpty(combatWarn1.getCheckResult())) {
                                        combatBlog1.setImageAddress2(combatWarn1.getCheckResult());
                                    }
                                }
                            }
                            //视频定位
                            String videos = combatBlog1.getReportVideo();

                            if (StringUtils.isNotEmpty(videos) && StringUtils.isNotEmpty(city)) {
                                if (StringUtils.isNotEmpty(videos) && !videos.contains("combat")) {
                                    String[] split = videos.split(",");
                                    String path = "";
                                    Date reportime = combatBlog1.getReportime();
                                    String data = DateUtils.parseDateToStr("yyyyMMdd", reportime);
                                    for (int i = 0; i < split.length; i++) {
                                        int n = i + 1;
                                        if (StringUtils.isNotEmpty(path)) {
                                            path = path + ",/combat/" + data + " _" + combatBlog1.getId() + "_" + n + ".mp4";
                                        } else {
                                            path = "/combat/" + data + " _" + combatBlog1.getId() + "_" + n + ".mp4";
                                        }
                                        if (split.length == 1) {
                                            path = "/combat/" + data + " _" + combatBlog1.getId() + ".mp4";
                                        }
                                    }

                                    byte[] download = sysFileService.download(path);
                                    byte[] videoPic = JavacvUtils.getVideoPic(download);

//                                    FileUtil.writeBytes(videoPic, "C:\\Users\\HYZ\\Desktop\\1233.jpg");
                                    String imgBase64 = Base64.getEncoder().encodeToString(videoPic);
                                    CombatWarn combatWarn1 = combatCrawlService.checkWeiboVideo(49L, userId, imgBase64, city);
                                    if (combatWarn1.getLocationLat() != null) {
                                        if (checkData(blogId)) {
                                            combatWarn1.setBlogId(combatBlog1.getBlogId());
                                            combatWarnService.insertCombatWarn(combatWarn1);
                                        }
                                    }
                                    if (StringUtils.isNotEmpty(combatWarn1.getCheckResult())) {
                                        combatBlog1.setImageAddress2(combatWarn1.getCheckResult());
                                    }
                                }

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    combatBlog1.setStatus("1");
                    combatBlogService.updateCombatBlog(combatBlog1);
                }
                //检测用户社交关系
//                checkUserRelation(userId);
            }
        }
    }

    public String getCity(String str) {
        if (StringUtils.isEmpty(str)) {
            return "";
        }
        String city = sysConfigService.selectConfigByKey("city");
        String[] split = city.split(",");
        String result = "";
        for (String s : split) {
            if (str.contains(s)) {
                result = s;
                break;
            }
        }
        if (StringUtils.isEmpty(result)) {
            result = str;
        }
        return result;
    }

    /**
     * 检测用户博文是否检测
     * @param blogId
     * return true 未检测 false 检测
     */
    public boolean checkData(String blogId) {
        CombatWarn combatWarn = new CombatWarn();
        combatWarn.setBlogId(blogId);
        List<CombatWarn> combatWarns = combatWarnService.selectCombatWarnList(combatWarn);
        return combatWarns.size() == 0;
    }

    /**
     * 下载网络图片
     *
     * @param urlList 网络路径
     */
    public byte[] downloadPicture(String urlList) {
        URL url = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] byteArray = output.toByteArray();
            dataInputStream.close();
            return byteArray;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getCity1(String text) {
        return CityUtil.getCity(text);
    }


}
